<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\5\4 0004
 * Time: 16:35
 */

namespace App\Http\BackendControllers;

use App\Models\Admin;
use App\Models\Role;
use App\Services\AdminService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;


class AdminController extends Controller
{
    public function index()
    {
        $data = Admin::with('roles')->paginate(15);
        $roles = Role::all();
        return view('backend.admin.index', compact('data','roles'));
    }


    public function store(Request $request)
    {
        $data = $request->only('account', 'password', 'repassword','roles');
        $id = $request->input('id');

        $rules = [
            'account' => 'required',
            'password' => 'required|between:6,12',
            'repassword' => 'required|same:password',
            'roles' => 'required|array'
        ];
        $message = [
            "account.required" => "请输入用户名",
            "password.required" => "请输入密码",
            "repassword.required" => "请输入确认密码",
            "account.unique" => "用户名已存在",
            "repassword.same" => "两次密码不一致",
            "password.between" => "密码长度不在6-12位之间",
            "roles.required" => "请勾选账户角色",
            "roles.array" => "角色id需要传入数组",
        ];
        $validator = Validator::make($data, $rules, $message);
        if ($validator->fails()) {
            return err('',$validator->errors()->first());
        }
        $roles = $data['roles'];
        unset($data['repassword'],$data['roles']);
        $data['password'] = bcrypt($data['password']);

        if ($id) {
            $admin = Admin::where('id', $id)->first();
            AdminService::adminRole($admin,$roles);
            $admin->update($data);
        } else {
            $admin = Admin::create($data);
            $admin->roles()->attach($roles);
        }
        return res('', '提交成功');
    }


    public function destroy(Request $request)
    {
        $id = $request->only('id');
        $admin = Admin::where('id',$id)->first();
        $admin->roles()->detach();
        $admin->delete();
        return res('','删除成功');
    }


}